<?php
/**
 * Created by 后台公共类.
 * User: 尚金殿
 * Date: 2018/8/20
 * Time: 10:43
 */

namespace app\admin\controller;


use think\Controller;
use think\Db;
use think\Request;


class CommonController extends Controller
{
    protected $session = array();//获取session
    protected $menu = array();   //获取菜单

    protected $mysql = '';    //表名
    protected $pk = '';       //主键
    protected $name = '';     //模糊匹配
    protected $status = '';   //状态名

    //初始化
    public function _initialize(){
        //判断是否登陆了
        $isLogin = $this->isLogin();
        if(!$isLogin){
            $this->redirect('/admin.php/login/lists');
        }
        //验证权限
        $this->getAdminUserByRuleId();
    }

    //获取用户信息
    public function getLoginUser()
    {
        $this->session = session('TourAdminUser');
        return $this->session;
    }


    //判定用户是否登陆
    public function isLogin()
    {
        $user = $this->getLoginUser();
        if($user && is_array($user)){
            return true;
        }
        return false;
    }

    //验证权限
    public function getAdminUserByRuleId(){

        if($this->session['group_id'] != 1){
            //获取当前用户的权限
            $group = Db::name('group')->where('group_id',$this->session['group_id'])->find();
            if(!is_numeric($group['rule_id'])){
                //不为数字
                $group['rule_id'] = explode(',',$group['rule_id']);
            }

            //获取当前用户的权限
            $userRule = array();

            foreach($group['rule_id'] as $k => $v){
                $rule = Db::name('rule')->where('rule_id','=',$v)->where('rule_status','>',-1)->find();
                //获取权限
                $userRule[] = $rule['rule_url'];
                //获取菜单
                if($rule['rule_status'] == 1){
                    $this->menu[] = $rule;
                }
            }

            //获取当前方法
            $nowRule = strtolower($this->request->controller()).'/'.$this->request->action();

            //不需要验证的方法
            $noRule = array('index/lists','login/lists','login/loginOut');
            //合并不需要验证的方法和当前用户的权限
            $norule = array_merge($noRule,$userRule);
            //判定权限
            if(!in_array($nowRule,$noRule)){
                echo "<script>alert('没有权限,请联系管理员开通');location.href='/admin.php'</script>";
            }

        }else{
            //超级管理员
            $this->menu = Db::name('rule')->where(['rule_status'=>1])->order('rule_id')->select();
        }
        $this->assign('menu',$this->menu);

    }

    /**********************************************增删改查********************************************************/

    //加载列表
    public function lists(){
        $keyWord = Request::instance()->param('key_word');

        //关键词
        if(!empty($keyWord)){
            $res = Db::name($this->mysql)->where($this->name,'like',$keyWord.'%')->where($this->status,'>',-1)->paginate(10);
        }else{
            $res = Db::name($this->mysql)->where($this->status,'>',-1)->paginate(10);
        }


        $this->assign('key_word',$keyWord);
        $this->assign('res',$res);
        return $this->fetch();
    }

    //添加
    public function getAdd($data){
        $data['create_time'] = $data['update_time'] = time();
        return Db::name($this->mysql)->insertGetId($data);
    }

    //编辑
    public function getEdit($id){

        $rule = Db::name($this->mysql)->find($id);

        return $rule;
    }

    public function save($data){
        if(!$data || !is_array($data)){
            return show(0,'传递的数据不合法');
        }

        $id = $data[$this->pk];
        unset($data[$this->pk]);
        $data['update_time'] = time();

        $res = Db::name($this->mysql)->where($this->pk,$id)->update($data);

        if(!$res){
            return show(0,'更新失败');
        }
        return show(1,'更新成功');
    }

    //删除数据(修改状态)
    public function setStatus(){
        $id = Request::instance()->param('id');
        $data[$this->status] = Request::instance()->param('status');
        $data['update_time'] = time();

        $res = Db::name($this->mysql)->where($this->pk,$id)->update($data);

        if(!$res){
            return show(0,'操作失败');
        }
            return show(1,'操作成功');
    }

    //更新排序
    public function updateSort(){
        //获取数据
        $sort = Request::instance()->param();

        //定义跳转地址
        $jumpUrl = $_SERVER['HTTP_REFERER'];

        //定义一个空数组准备接收更新排序失败的ID
        $errors = array();

        //判定是否有值
        if($sort || is_array($sort)){

            //循环进行更新数据
            foreach($sort['sort'] as $scrapId => $v){
                $data['update_time'] = time();
                $data['sort'] = $v;
                $id = Db::name($this->mysql)->where($this->pk,$scrapId)->update($data);
                if($id === false){
                    $errors[] = $scrapId;
                }
            }
            if($errors){
                return show(0,'排序失败-'.import(',',$errors),array('jump_url' => $jumpUrl));
            }
            return show(1,'排序成功',array('jump_url' => $jumpUrl));
        }

        return show(0,'没有提交的数据');
    }

    /**********************************************图片上传********************************************************/
    //图片异步上传
    public function ajaxUploadImage(){
        $tpl = $this->request->param('tpl');
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');

        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( './uploads');

        //获取上传的图片路径
        $path[] = 'https://'.$_SERVER['HTTP_HOST'].'/uploads/'.str_replace('\\','/',$info->getSaveName());

        echo $this->getUploadTpl($path,$tpl);
    }

    //异步加载图片
    public function ajaxImage(){

        $path = $this->request->param('path');
        $path = explode(',',$path);
        $tpl = $this->request->param('tpl');
        echo $this->getUploadTpl($path,$tpl);
    }

    public function getUploadTpl($path,$tpl = null){
        $this->assign('path',$path);
        return $this->fetch($tpl);
    }

    //图片异步删除
    public function ajaxDel(){
        //获取传递的变量
        $path = $this->request->param('path');
        $lenth = strlen('https://'.$_SERVER['HTTP_HOST']);

        //截取字符串
        $path = substr($path,$lenth);
        $path = '.'.$path;
        //判断是不是文件
        if(is_file($path)){
           unlink($path);
        }

    }
}